package com.yyk.yiliao.ui.mine.fragment;

import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseFragment;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.listener.DialogSureCancelListenter;
import com.yyk.yiliao.mvvm.ui.MineActivity;
import com.yyk.yiliao.ui.Main_Activity;
import com.yyk.yiliao.ui.activity.dingdan.activity.CommodityOrde_Activity;
import com.yyk.yiliao.ui.gongyong.activity.Reportquery_Activity;
import com.yyk.yiliao.ui.gongyong.activity.WebViewActivity;
import com.yyk.yiliao.ui.message.ConversationListActivity;
import com.yyk.yiliao.ui.mine.activity.CardWei_Activity;
import com.yyk.yiliao.ui.mine.activity.Identity_Activity;
import com.yyk.yiliao.ui.mine.activity.PersonnelSelection2_Activity;
import com.yyk.yiliao.ui.mine.activity.Registration_Activity;
import com.yyk.yiliao.ui.mine.activity.Set_Activity;
import com.yyk.yiliao.ui.trade.MyAccountActivity;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.glide.GlideUtils;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.UserbankUsersInfo;
import com.yyk.yiliao.widget.CircleImageView;
import com.yyk.yiliao.widget.LinePagerIndicatorDecoration;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/6/15 0015.
 * 我的界面
 */

public class Mine_Fragment extends BaseFragment {

    public boolean flagOnclick = false;  //判断 工作室 是否创建，否则会造成fagment没有实列化

    @BindView(R.id.nMine_set)
    ImageView nMineSet;
    @BindView(R.id.nMine_identity)
    TextView nMineIdentity;
    @BindView(R.id.mMine_name)
    TextView mMineName;
    @BindView(R.id.nMine_identity2)
    TextView nMineIdentity2;

    @BindView(R.id.nMine_dd_one)
    LinearLayout nMineDdOne;
    @BindView(R.id.nMine_dd_three)
    LinearLayout nMineDdThree;

    @BindView(R.id.nMine_ll)
    LinearLayout nMineLl;
    @BindView(R.id.nMine_wdjk)
    RecyclerView nMineWdjk;
    @BindView(R.id.nMine_gj_jiuzhenren)
    LinearLayout nMineGjJiuzhenren;
    @BindView(R.id.nMine_dd_two)
    LinearLayout nMineDdTwo;
    @BindView(R.id.nMine_dd_four)
    LinearLayout nMineDdFour;
    @BindView(R.id.nMine_dd_five)
    LinearLayout nMineDdFive;
    @BindView(R.id.nMine_registration)
    LinearLayout nMineRegistration;
    @BindView(R.id.wdgj_1)
    LinearLayout wdgj1;
    @BindView(R.id.wdgj_3)
    LinearLayout wdgj3;
    @BindView(R.id.wdgj_4)
    LinearLayout wdgj4;
    @BindView(R.id.wdgj_5)
    LinearLayout wdgj5;
    @BindView(R.id.wdgj_6)
    LinearLayout wdgj6;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    @BindView(R.id.iv_yuandian)
    ImageView ivYudian;
    @BindView(R.id.nMine_icon)
    CircleImageView nMineIcon;
    @BindView(R.id.ll_yue)
    LinearLayout llYue;
    @BindView(R.id.tv_yue)
    TextView tvYue;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_mine;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {
        initPic();
        initAdapter();
    }

    /**
     * 设置头像
     */
    private void initPic() {
        if (Hawk.contains("wxpic")) {
            GlideUtils.loadTouxiang(getActivity(), ApiService.BASE_URL + Hawk.get("wxpic") + "", nMineIcon);
        }

    }

    private void initAdapter() {
        setWdjk();
    }

    /**
     * 患者 余额
     */
    private void initPostUserbankUsers() {
        Map<String, String> map = new TreeMap<>();
        map.put("id", Hawk.get("uid") + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postUserbankUsers(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<UserbankUsersInfo>() {
                    @Override
                    public void onCompleted() {
                        //完成的时候调用
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(UserbankUsersInfo info) {
                        Logger.e("患者主页" + info.toString());
                        float money = info.getData().getMoney();
                        DecimalFormat decimalFormat = new DecimalFormat("0.00");

                        tvYue.setText(decimalFormat.format(money) + "");

                    }
                });
    }

    /**
     * 我的健康
     */
    private void setWdjk() {
        List<String> list = new ArrayList<>();
        list.add("1");
        BaseRecyclerAdapter<String> wdjk = new BaseRecyclerAdapter<String>(getActivity(), list, R.layout.adapter_item_mine_wdjk) {
            @Override
            public void convert(BaseRecyclerHolder holder, String item, int position, boolean isScrolling) {

            }
        };
        nMineWdjk.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        nMineWdjk.setAdapter(wdjk);
        // 添加PagerSnapHelper
        PagerSnapHelper snapHelper = new PagerSnapHelper();
        snapHelper.attachToRecyclerView(nMineWdjk);
        // pager indicator
        nMineWdjk.addItemDecoration(new LinePagerIndicatorDecoration());

    }

    /**
     * 这里实现 用户是否认证
     */
    private void initLogin() {
        final String real = Hawk.get("real");//身份认证
        final String statusfo = Hawk.get("statusfo"); //鲁亿通
        Logger.i("鲁亿通 参数：" + statusfo);
        final String real_name = Hawk.get("real_name");//姓名
        final String phone = Hawk.get("phone");//手机号码
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(real)) {
                    if (real.equals("1")) {
                        nMineIdentity.setVisibility(View.VISIBLE);
                        nMineIdentity2.setVisibility(View.GONE);

                    } else {
                        nMineIdentity.setVisibility(View.GONE);
                        nMineIdentity2.setVisibility(View.VISIBLE);
                    }
                }
                if (!TextUtils.isEmpty(phone)) {
                    mMineName.setText(phone);
                    if (!TextUtils.isEmpty(real_name)) {
                        mMineName.setText(real_name);
                    }
                }
            }
        });


    }


    /**
     * 实现 消息提醒圆点变化
     */
    @Override
    public void onResume() {
        super.onResume();
        //余额
        initPostUserbankUsers();

        flagOnclick = true;
        //更新界面
        initLogin();
        refreshUIWithMessage();
        //更新mainactivity的消息数量
        ((Main_Activity) getActivity()).updateUnreadLabel();

    }


    public void refreshUIWithMessage() {
        getActivity().runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
            }
        });
    }

    /**
     * 1.更新环信发送的消息数量
     */
    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            ivYudian.setVisibility(View.VISIBLE);
        } else {
            ivYudian.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 获取消息数量
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        return EMClient.getInstance().chatManager().getUnreadMsgsCount();
    }

    @OnClick({R.id.wdgj_1, R.id.wdgj_3, R.id.wdgj_4, R.id.wdgj_5, R.id.wdgj_6, R.id.nMine_dd_five, R.id.nMine_set, R.id.nMine_gj_jiuzhenren, R.id.nMine_card, R.id.nMine_registration, R.id.nMine_identity, R.id.nMine_identity2, R.id.nMine_dd_one, R.id.nMine_dd_two, R.id.nMine_dd_three, R.id.nMine_dd_four

            , R.id.iv_message, R.id.ll_yue})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.nMine_set:

                startAct(Set_Activity.class);
                break;
            case R.id.nMine_gj_jiuzhenren:

                startAct(PersonnelSelection2_Activity.class);
                break;
            case R.id.nMine_card:
                //身份认证状态
                String statusfo = Hawk.get("statusfo");
                Intent intent2 = new Intent(getActivity(), WebViewActivity.class);
                intent2.putExtra("toolbar_tv", "鲁医通卡预约办理");
                intent2.putExtra("url", ApiService.H5_URL + "/views/Login/Cardlogin.html?from=app&Sources=3");
                startActivity(intent2);
                break;
            case R.id.nMine_dd_one:

                startAct(Registration_Activity.class);
                break;
            case R.id.nMine_dd_two:
                startActivity(new Intent(getActivity(), Reportquery_Activity.class).putExtra("caonima", "我的问诊"));
                break;
            case R.id.nMine_dd_three:
                Intent intentThree = new Intent(getActivity(), CommodityOrde_Activity.class);
                //                intentThree.putExtra("tab_id", 3);
                startActivity(intentThree);
                break;
            case R.id.nMine_dd_four:
                startActivity(new Intent(getActivity(), Reportquery_Activity.class).putExtra("caonima", "处方"));

                break;
            case R.id.nMine_dd_five:
                Intent iv_srys = new Intent(getActivity(), WebViewActivity.class);
                iv_srys.putExtra("toolbar_tv", "私人医生");
                iv_srys.putExtra("url", ApiService.H5_URL + "views/Tabs/privatedoctor.html?from=app" + "&Sources=3");
                startActivity(iv_srys);

                break;
            case R.id.nMine_registration:
                break;

            case R.id.nMine_identity:
                //身份认证状态
                String real = Hawk.get("real");
                if (real.equals("1")) {
                    startActivity(new Intent(getActivity(), CardWei_Activity.class));
                }
                break;
            case R.id.nMine_identity2:
                //身份未认证状态
                String real2 = Hawk.get("real");
//                if (real2.equals("2")) {
                startActivity(new Intent(getActivity(), Identity_Activity.class));
//                }
                break;

            case R.id.wdgj_1:
                Intent home_top3 = new Intent(getActivity(), WebViewActivity.class);
                home_top3.putExtra("toolbar_tv", "慢病管理");
                home_top3.putExtra("url", ApiService.H5_URL + "views/Tabs/chronic.html?from=app" + "&Sources=3");
                startActivity(home_top3);
                break;
            case R.id.wdgj_3:
                startActivity(new Intent(getActivity(), Reportquery_Activity.class).putExtra("caonima", "报告查询"));

                break;
            case R.id.wdgj_4:
                Intent iv_bxfw = new Intent(getActivity(), WebViewActivity.class);
                iv_bxfw.putExtra("toolbar_tv", "保险服务");
                iv_bxfw.putExtra("url", ApiService.H5_URL + "views/Tabs/insurance.html?from=app" + "&Sources=3");
                startActivity(iv_bxfw);
                break;
            case R.id.wdgj_5:
                startActivity(new Intent(getActivity(), Reportquery_Activity.class).putExtra("caonima", "我的评论"));

                break;
            case R.id.wdgj_6:
                startActivity(new Intent(getActivity(), Reportquery_Activity.class).putExtra("caonima", "入驻申请"));

                break;
            case R.id.iv_message:
                startAct(ConversationListActivity.class);
//                startAct(MineActivity.class);
                break;
            //充值和体现体系
            case R.id.ll_yue:
                if (Hawk.get("real").equals("1")) {
                    startAct(MyAccountActivity.class);
                } else {
                    DialogUtil.getIntanse().showReturnTips(getActivity(), "", "您的账号还未实名认证", "立即认证", "取消", new DialogSureCancelListenter() {
                        @Override
                        public void onSureListenter() {
                            startAct(Identity_Activity.class);
                        }

                        @Override
                        public void onCancelListenter() {

                        }
                    }, false);

                }


                break;

        }
    }

}
